﻿using System;
using System.Collections.Generic;
using Microsoft.SharePoint.Administration;
using System.Linq;
using SPContrib.Extensions;

namespace SPContrib.SharePoint.Extensions
{
    /// <summary>
    /// Extensions for the SPFarm class
    /// </summary>
    public static class SPFarmExtensions
    {
        /// <summary>
        /// Query the farm for a SPWebApplication that meets the id criteria
        /// </summary>
        /// <param name="id">the id of the SPWebApplication</param>
        public static SPWebApplication FindWebApplicationById(this SPFarm instance, Guid id)
        {
            SPWebApplication result;
            bool match = instance
                            .FindWebApplicationsByCriteria(wa => wa.Id == id)
                            .Execute(out result);

            if (match == false)
            {
                throw "SPFarmExtensions: failed to find a webapplication with id '{0}'"
                        .AsException(id);
            }

            return result;
        }

        /// <summary>
        /// Query the farm for SPWebApplications that meet the search criteria
        /// </summary>
        /// <param name="criteria">the search criteria delegate (e.g. wa => wa.Name == "SomeName")</param>
        public static IEnumerable<SPWebApplication> FindWebApplicationsByCriteria(this SPFarm instance, Predicate<SPWebApplication> criteria)
        {
            return from SPWebApplication wa in instance.Services.GetValue<SPWebService>().WebApplications
                   where criteria(wa)
                   select wa;

        }
    }
}
